package com.xlhj.boot.service.impl;

import com.xlhj.boot.service.DelayedProducerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author: liucaijing
 * @description: 延迟队列(插件实现)
 * @date: 2021/10/20 9:01
 */
@Service
public class DelayedProducerServiceImpl implements DelayedProducerService {

    private static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
    private static final String DELAYED_ROUT_KEY = "delayed.routingkey";

    private static Logger logger = LoggerFactory.getLogger(DelayedProducerServiceImpl.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendMessage(String message, Integer delayTime) {
        String uuid = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData(uuid);
        rabbitTemplate.convertAndSend(DELAYED_EXCHANGE_NAME, DELAYED_ROUT_KEY, message, processor -> {
            processor.getMessageProperties().setDelay(delayTime);
            return processor;
        }, correlationData);
        logger.info("发送一条延时：{}毫秒的消息：{}给队列delayed.queue", delayTime, message);
    }
}
